package com.ms.controller;

import com.ms.entity.User;
import com.ms.entity.Organizer;
import com.ms.entity.Event;
import com.ms.entity.Manager;
import com.ms.service.inter.EventService;
import com.ms.utils.SimpleTokenUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 比赛控制器 - 处理比赛相关的HTTP请求
 * 包括比赛信息查询、报名等功能
 */
@RestController
@RequestMapping("/event")
//@CrossOrigin(origins = "http://localhost:8080")
// 允许跨域请求
public class EventController {

    @Autowired
    private EventService eventService;

    /**
     * 获取所有比赛项目列表
     * @param request HTTP请求
     * @return 比赛列表
     */
    @GetMapping("/getListAll")
    public ResponseEntity<Map<String, Object>> getAllEvents(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (userObj == null) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            List<Event> events = eventService.findAll();
            result.put("success", true);
            result.put("events", events);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取比赛列表失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }


    /**
     * 根据项目ID获取比赛项目详情
     * @param eventId 项目ID
     * @param request HTTP请求
     * @return 项目详情
     */
    @GetMapping("/detail")
    public ResponseEntity<Map<String, Object>> getEventById(@RequestParam String eventId, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            // 修改：允许User、Manager、Organizer三种身份访问
            if (!(userObj instanceof User) && !(userObj instanceof Manager) && !(userObj instanceof Organizer)) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            Event event = eventService.findById(eventId);
            if (event == null) {
                result.put("success", false);
                result.put("message", "比赛不存在");
                return ResponseEntity.badRequest().body(result);
            }

            result.put("success", true);
            result.put("event", event);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取比赛详情失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }



    /**
     * 根据类别获取比赛项目列表
     * @param category 比赛类别
     * @param request HTTP请求
     * @return 比赛列表
     */
    @GetMapping("/ByCategory")
    public ResponseEntity<Map<String, Object>> getEventsByCategory(@RequestParam String category, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            // 修改：允许User、Manager、Organizer三种身份访问
            if (!(userObj instanceof User) && !(userObj instanceof Manager) && !(userObj instanceof Organizer)) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            List<Event> events = eventService.findByCategory(category);
            result.put("success", true);
            result.put("events", events);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取比赛列表失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }


    /**
     * 根据比赛ID获取所有项目
     * @param gameId 比赛ID
     * @param request HTTP请求
     * @return 项目列表
     */
    @GetMapping("/getGameEvent")
    public ResponseEntity<Map<String, Object>> getEventsByGameId(@RequestParam String gameId, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            // 修改：允许User、Manager、Organizer三种身份访问
            if (!(userObj instanceof User) && !(userObj instanceof Manager) && !(userObj instanceof Organizer)) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            List<Event> events = eventService.findByGameId(gameId);
            result.put("success", true);
            result.put("events", events);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取比赛项目列表失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }


    /**
     * 主办方添加/更新比赛项目
     * @param event 比赛项目对象
     * @param request HTTP请求
     * @return 添加结果
     *
     * 如果需要更新则传入eventId
     * 如果需要添加则无需存入eventId
     */
    @PostMapping("/save")
    public ResponseEntity<Map<String, Object>> saveEvent(@RequestBody Event event, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof Organizer)) {
                result.put("success", false);
                result.put("message", "无权限访问，仅主办方可以添加比赛项目");
                return ResponseEntity.badRequest().body(result);
            }

            // 保存比赛项目
            boolean success = eventService.saveEvent(event);
            if (success) {
                result.put("success", true);
                result.put("message", "比赛项目保存成功");
                // 返回保存后的对象，包含生成的ID等信息
                result.put("event", event);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "比赛项目保存失败");
                return ResponseEntity.internalServerError().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "比赛项目保存失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }



    /**
     * 用户报名比赛
     * @param registrationData 报名数据，包含比赛ID
     * @param request HTTP请求
     * @return 报名结果
     */
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> registerEvent(@RequestBody Map<String, String> registrationData, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof User)) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            User currentUser = (User) userObj;
            String userId = String.valueOf(currentUser.getUserID());

            // 🎯 修复：检查 eventId 是否存在
            String eventId = registrationData.get("eventId");
            if (eventId == null || eventId.isEmpty()) {
                result.put("success", false);
                result.put("message", "比赛ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            // 检查用户是否已报名该比赛
            if (eventService.isUserRegistered(userId, eventId)) {
                result.put("success", false);
                result.put("message", "您已经报名过这个比赛了");
                return ResponseEntity.badRequest().body(result);
            }

            // 执行报名操作
            boolean registrationSuccess = eventService.registerUserForEvent(userId, eventId);

            // 🎯 修复：根据操作结果返回响应
            if (registrationSuccess) {
                result.put("success", true);
                result.put("message", "报名成功");
                // 🎯 确保返回 200 状态码
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "报名失败，请稍后重试");
                return ResponseEntity.ok(result); // 🎯 业务失败也返回 200，避免 500 错误
            }
        } catch (Exception e) {
            // 🎯 修复：异常处理也要返回正确的状态码
            result.put("success", false);
            result.put("message", "报名失败: " + e.getMessage());
            // 🎯 返回 200 状态码，避免前端收到 500 错误
            return ResponseEntity.ok(result);
        }
    }


    /**
     * 获取用户已报名的比赛列表
     * @param request HTTP请求
     * @return 已报名的比赛列表
     */
    @GetMapping("/user")
    public ResponseEntity<Map<String, Object>> getUserEvents(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof User)) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            User currentUser = (User) userObj;
            // 修改：使用修改后的User类的获取ID方法
            String userId = String.valueOf(currentUser.getUserID());

            List<Event> events = eventService.findEventsByUserId(userId);
            result.put("success", true);
            result.put("events", events);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取报名记录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }


    /**
     * 取消报名
     * @param registrationData 取消报名数据，包含比赛ID
     * @param request HTTP请求
     * @return 取消结果
     */
    @PostMapping("/cancel")
    public ResponseEntity<Map<String, Object>> cancelRegistration(@RequestBody Map<String, String> registrationData, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        String eventId = registrationData.get("eventId");

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof User)) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            User currentUser = (User) userObj;
            // 修改：使用修改后的User类的获取ID方法
            String userId = String.valueOf(currentUser.getUserID());

            // 检查用户是否已报名该比赛
            if (!eventService.isUserRegistered(userId, eventId)) {
                result.put("success", false);
                result.put("message", "您还没有报名这个比赛");
                return ResponseEntity.badRequest().body(result);
            }

            // 执行取消报名操作
            eventService.cancelRegistration(userId, eventId);

            result.put("success", true);
            result.put("message", "取消报名成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "取消报名失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 主办方删除比赛项目
     * @param eventId 比赛项目ID
     * @param request HTTP请求
     * @return 删除结果
     */
    @DeleteMapping("/delete")
    public ResponseEntity<Map<String, Object>> deleteEvent(@RequestParam Integer eventId, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof Organizer)) {
                result.put("success", false);
                result.put("message", "无权限访问，仅主办方可以删除比赛项目");
                return ResponseEntity.badRequest().body(result);
            }

            // 删除比赛项目
            boolean success = eventService.deleteEvent(eventId);
            if (success) {
                result.put("success", true);
                result.put("message", "比赛项目删除成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "比赛项目删除失败");
                return ResponseEntity.internalServerError().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "比赛项目删除失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
    
    /**
     * 根据比赛项目ID获取所有报名信息及用户信息
     * @param eventId 比赛项目ID
     * @param request HTTP请求
     * @return 报名信息列表，包含用户详细信息
     */
    @GetMapping("/registrations")
    public ResponseEntity<Map<String, Object>> getRegistrationsWithUserInfo(@RequestParam Integer eventId, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof Organizer)) {
                result.put("success", false);
                result.put("message", "无权限访问，仅主办方可以查看报名信息");
                return ResponseEntity.badRequest().body(result);
            }

            // 获取报名信息及用户信息
            List<Map<String, Object>> registrations = eventService.getRegistrationsWithUserInfo(String.valueOf(eventId));
            
            result.put("success", true);
            result.put("registrations", registrations);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取报名信息失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据token获取主办方ID，然后获取该主办方的所有比赛及其项目信息
     * @param request HTTP请求
     * @return 主办方的比赛及项目信息
     */
    @GetMapping("/gamesEvents")
    public ResponseEntity<Map<String, Object>> getOrganizerGamesAndEvents(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof Organizer)) {
                result.put("success", false);
                result.put("message", "无权限访问，仅主办方可以查看");
                return ResponseEntity.badRequest().body(result);
            }

            Organizer organizer = (Organizer) userObj;
            Integer organizerId = organizer.getOrId();
            System.out.println("000000000000000000000000000000000000001232141234");
            // 获取主办方的所有比赛及其项目信息
            List<Map<String, Object>> gamesAndEvents = eventService.getGamesAndEventsByOrganizerId(organizerId);

            result.put("success", true);
            result.put("data", gamesAndEvents);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取比赛及项目信息失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}